capture program drop rdd_plot
program define rdd_plot
	version 9.1
	syntax varlist [if] [in] , xtitle(string) bw(real) includedbw(real) title(string) control(varlist) binsize(real)  [yscale(string ) ]  

marksample touse
preserve
****************************************************************************************************************************************************************
qui keep if `touse'
tokenize "`varlist'"
local variable `1' 
tokenize "`control'"
local c `1'
tempvar mean
tempvar bin
tempvar freq	

tempvar ul0
tempvar ll0

tempvar ul1
tempvar ll1

tempvar x0
tempvar s0
tempvar se0
tempvar x1
tempvar s1
tempvar se1

tempvar fordisc
tempvar diff

****************************************************************************************************************************************************************

replace margin_1=-0.0001 if margin_1==0 & elected_women==0
replace margin_1=0.0001 if margin_1==0 & elected_women==1
	
****************************************************************************************************************************************************************
	
	

****************************************************************************************************************************************************************
gen `bin'=`c'-mod(`c',`binsize')+`binsize'/2



egen `freq'  = total(1) , by(`bin')
	
egen `mean'=mean(`variable'), by(`bin')


****************************************************************************************************************************************************************




qui: lpoly `variable' `c' if `c'<0  , bw(`bw') deg(1)  n(100) gen(`x0' `s0') ci se(`se0') kernel( triangle  )
qui: lpoly `variable' `c' if `c'>=0 , bw(`bw')  deg(1)   n(100) gen(`x1' `s1') ci se(`se1') kernel( triangle  )



forvalues v=0/1 {
		gen `ul`v'' = `s`v'' + 1.645*`se`v''
		gen `ll`v'' = `s`v'' - 1.645*`se`v'' 
	}
	
	
****************************************************************************************************************************************************************



qui: tw (rarea  `ul0' `ll0' `x0' if abs(`x0')<`includedbw', bcolor(gs14) ) (rarea  `ul1' `ll1' `x1' if abs(`x1')<`includedbw', bcolor(gs14) ) (scatter `mean' `bin' [fw=`freq'] if abs(`bin')<`includedbw', msymbol(oh) msize(medium)    mcolor(black) )  (line `s0' `ul0' `ll0' `x0' if abs(`x0')<`includedbw', lwidth(thick) lcolor(red bluishgray bluishgray) lpattern(solid solid solid) )   (line `s1' `ul1' `ll1' `x1' if abs(`x1')<`includedbw', lwidth(thick) lcolor(red bluishgray bluishgray) lpattern(solid solid solid) ) , legend(off)  ytitle(`"`title'"')  xline(0) ylabel(`yscale',format(%9.0g) labsize(small) labgap(1) angle(horizontal)) xlabel(-0.15(0.05)0.15)   xtitle(`"`xtitle'"')  graphregion(color(white) lwidth(large)) graphr(m(large))

****************************************************************************************************************************************************************

restore
end	


